package com.beeasy.hzbpm.bpm;

import com.beeasy.hzbpm.bean.MQService;
import com.beeasy.hzbpm.ctrl.workflow;
import com.beeasy.hzbpm.entity.BpmInstance;
import com.beeasy.hzbpm.filter.Auth;
import com.github.llyb120.json.Json;
import com.github.llyb120.json.Obj;

import javax.jms.TextMessage;

import static com.github.llyb120.json.Json.o;

public final class BpmMQ {
    public static void start(){
        MQService.instance.listenMessage(MQType.TOPIC, BPMCommand.START_BPM, e -> {
            TextMessage textMessage = (TextMessage) e;
            startBpm(textMessage.getText());
        });;

        MQService.instance.listenMessage(MQType.TOPIC, BPMCommand.NOTIFY_START_BPM_OK, e -> {
            TextMessage textMessage = (TextMessage) e;
            System.out.println(textMessage.getText());
        });


        MQService.instance.listenMessage(MQType.TOPIC, BPMCommand.NOTIFY_END_RESULT, e -> {
            TextMessage textMessage = (TextMessage) e;
            System.out.println(textMessage.getText());
        });
    }

    public static void startBpm(String msg){
        try{
            Obj data = Json.parse(msg);
            if (data == null) {
                throw new RuntimeException("数据错误，不是正确的json");
            }
            String id = data.ss("id");
            if(id.isEmpty()){
                throw new RuntimeException("流程ID不能为空");
            }
            String uid = data.ss("uid");
            if(uid.isEmpty()){
                throw new RuntimeException("流程处理人不能未空");
            }
            Obj args = data.oo("args");
            workflow wf = new workflow();
            Auth.setUid(uid);
            BpmInstance ret = wf.createInsNewToMQ(id, o("args", args));
            MQService.instance.sendMessage(MQType.TOPIC, BPMCommand.NOTIFY_START_BPM_OK, ret);
        } catch (Exception e){
            MQService.instance.sendMessage(MQType.TOPIC, BPMCommand.NOTIFY_START_BPM_ERROR, e.getMessage());
        }
    }

    public static void endBpm(Object  object){
        MQService.instance.sendMessage(MQType.TOPIC, BPMCommand.NOTIFY_END_RESULT, object);
    }
}
